import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { validatenull } from '@/utils/validate'
import authService from '@/utils/authservice'
import { tsParameterProperty } from '@babel/types';

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/jxslogin', '/elogin', '/gyslogin', '/401'] // no redirect whitelist
let i = 0
router.beforeEach(async (to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  //const hasToken = store.getters.token;
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    }
    else {
      try {
        await store.dispatch('user/getUserInfoByUPN')
        const { data } = await store.dispatch('permission/getUserPermission')

        var resutl = [];
        resutl = data.map(function (itme) {
          //此处配置当前站点code值
          if (itme.platformType == 'Admin') {
            return "yes"
          }
          else {
            return "no"
          }
        })
        if (resutl.indexOf("yes") >= 0) {
          //next()//有访问权限
          if (store.state.permission.routes == null || store.state.permission.routes.length == 0) {
            let routes = []
            data.map(function (itme) {
              //此处配置当前站点code值
              if (itme.platformType == 'Admin') {
                routes = itme
              }
            })
            store.dispatch('permission/generateRoutes', routes).then(val => {
              val.push({
                path: '*',
                redirect: '/404'
              })
              router.addRoutes(val)
              next({ ...to, replace: true })
              if (to.path == '/404') {
                if (to.redirectedFrom == '/login') next('/')
                else {
                  router.push(to.redirectedFrom)
                }
              }
            }).catch((_err) => {
              next()
            })
          } else {
            next()
          }
        } else {//无访问权限
          if (to.path.indexOf('401') !== -1) {
            next()
          } else {
            next('/401')
          }
        }
      } catch (error) {
        next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
